package linc.fun.openai.aspect;

import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import linc.fun.openai.annotation.Captcha;
import linc.fun.openai.exception.BizException;
import linc.fun.openai.helper.CaptchaHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * @author yqlin
 * @date 2023/3/6 12:38
 * @description
 */
@Aspect
@Component
@Slf4j
public class CaptchaAspect {

    public static final String UUID = "uuid";
    public static final String CODE = "code";
    @Resource
    private CaptchaHelper captchaHelper;

    @Before(value = "@annotation(captcha)", argNames = "captcha")
    public void captcha(Captcha captcha) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(attributes)) {
            throw BizException.MUST_HTTP_REQUEST;
        }
        HttpServletRequest request = attributes.getRequest();
        String code = request.getParameter(CODE);
        String uuid = request.getParameter(UUID);
        if (StrUtil.isBlank(uuid)) {
            throw BizException.CAPTCHA_UUID_BLANK;
        }
        if (StrUtil.isBlank(code)) {
            throw BizException.CAPTCHA_CODE_BLANK;
        }
        captchaHelper.verifyCaptcha(uuid, code);
    }

}
